'''
Author: admin@attacker.club
Date: 2023-03-31 02:13:55
LastEditTime: 2023-03-31 23:51:23
Description: 
pip3 install   elasticsearch==7
'''
import argparse
from elasticsearch import Elasticsearch
import datetime
def search_logs( time_range, index_name, query_string, es_url):
    es = Elasticsearch(es_url)
    # 查询信息和指定时间范围（相对时间）
    query = {
        "query": {
            "bool": {
                "must": [
                    {"match" : { "message" : query_string }}
                ],
                "filter": [
                    {"range":
                        {"@timestamp":
                            {"gte": f"now-{time_range}",
                             "lte": f"now"
                            }
                         }
                     }]
            }
        }
    }
    # result_set = es.search(index=index_name, body=query,size=1000)
    # return result_set['hits']['hits']
    result_set = es.search(index=index_name, body=query)
    return result_set['hits']['total']['value']
if __name__ == '__main__':
    # 定义参数解析器
    parser = argparse.ArgumentParser(description='Elasticsearch query script')
    parser.add_argument('--time', type=str,default='1h',
                        help='The relative time range to search within (e.g. 1h for the past hour)')
    
    parser.add_argument('--index', type=str,required=True,
                        help='The name of the Elasticsearch index to search in')
    parser.add_argument('--query', type=str,required=True,
                        help='The string to match in the log message')
    parser.add_argument('--es', type=str,
                        default="http://localhost:9200",
                        help='URL of ElasticSearch instance including port number (default: http://localhost:9200)')    
    # 解析参数并获取值
    args = parser.parse_args()
    time_range = args.time
    index_name=args.index
    query_string=args.query
    es_url=args.es
    
    results = search_logs(time_range, index_name, query_string, es_url)
    print(results)
    # 输出结果集合到控制台中显示
    # for log in results:
    #     print(log['_source']['message'])
    #     print('')